package com.sh169.action.user;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.pager.Pager;
import org.nutz.ioc.annotation.InjectName;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Files;
import org.nutz.lang.Strings;
import org.nutz.lang.random.StringGenerator;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.AdaptBy;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.upload.UploadAdaptor;

import com.sh169.actionform.ProductForm;
import com.sh169.beans.PageForm;
import com.sh169.beans.UserHolder;
import com.sh169.pojos.Brand;
import com.sh169.pojos.Classify;
import com.sh169.pojos.Message;
import com.sh169.pojos.Pinpai;
import com.sh169.pojos.Product;
import com.sh169.pojos.User;
import com.sh169.pojos.Vendor;
import com.sh169.util.ApplicationUtil;
import com.sh169.util.BaseHttpFilter;

@At("/vendor")
@IocBean(name="vendorHomeAction")
@InjectName("vendorHomeAction")
public class VendorHomeAction {
	public final static String IMAGE_UPLOAD_PATH = "/images/product/";
	private static final Log log = Logs.getLog(VendorHomeAction.class);
	
	@Inject("refer:dao")
	private Dao dao;
	public void setDao(Dao dao){
		this.dao = dao;
	}
	@At("/preupdate")
	@Ok("tiles:vendor.preupdate")
	public Vendor preUpdateVendor(HttpServletRequest request){
		UserHolder uh = (UserHolder) request.getSession().getAttribute(BaseHttpFilter.SECURITY_SESSION_USER);
		User user = dao.fetch(User.class,uh.getUsername());
		Vendor v = dao.fetch(Vendor.class,Cnd.where("userid","=",user.getId()));
		return v;
	}
	@At("/update")
	@Ok("redirect:/vendor/preupdate")
	public void updateVendor(@Param("::vendor.")Vendor vendor){
		Vendor temp = dao.fetch(Vendor.class,vendor.getId());
		temp.setAddress(vendor.getAddress());
		temp.setDescription(vendor.getDescription());
		temp.setHomeUrl(vendor.getHomeUrl());
		temp.setLinkMan(vendor.getLinkMan());
		temp.setLinkPhone(vendor.getLinkPhone());
		dao.update(temp);
	}
	@At("/product/preadd")
	@Ok("tiles:vendor.product.preadd")
	public ProductForm preUploadProduct(){
		ProductForm pf = new ProductForm();
		List<Classify> classifys = dao.query(Classify.class, null,null);
		List<Brand> brands = dao.query(Brand.class,null,null);
		List<Pinpai> pinpais = dao.query(Pinpai.class,null,null);
		pf.setClassifys(classifys);
		pf.setBrands(brands);
		pf.setPinpais(pinpais);
		return pf;
	}
	@At("/product/add")
	@Ok("tiles:vendor.product.addsuccess")
	@AdaptBy(type=UploadAdaptor.class,args={"E:/TomcatShare/temp"})
	public void uploadProduct(@Param("::product.")Product product,@Param("image")File image,HttpServletRequest request){
		UserHolder uh = (UserHolder) request.getSession().getAttribute(BaseHttpFilter.SECURITY_SESSION_USER);
		User user = dao.fetch(User.class,uh.getUsername());
		Vendor v = dao.fetch(Vendor.class,Cnd.where("userid","=",user.getId()));
		if(product!=null){
			product.setId(0);
			product.setVendorid(v.getId());
			product.setState(Product.STATE_ENABLE);
			if(image != null && !Strings.isEmpty(Files.getSuffixName(image))){
				String newFilePath =  IMAGE_UPLOAD_PATH+new StringGenerator(32, 32).next()+"."+Files.getSuffixName(image);
				try {
					Files.copyFile(image, new File(ApplicationUtil.getWebHomePath()+newFilePath));
					product.setImage(newFilePath);
				} catch (IOException e) {
					log.error("产品上传图片出错了", e);
				}
			}
			log.debug("insert the product");
			dao.fastInsert(product);
		}
	}
	@At("/product/manage")
	@Ok("tiles:vendor.product.manage")
	public PageForm<Product> manageProduct(@Param("pageNum")int pageNum,HttpServletRequest request){
		UserHolder uh = (UserHolder) request.getSession().getAttribute(BaseHttpFilter.SECURITY_SESSION_USER);
		User user = dao.fetch(User.class,uh.getUsername());
		Vendor v = dao.fetch(Vendor.class,Cnd.where("userid","=",user.getId()));
		Pager page = dao.createPager(pageNum<1?1:pageNum, 20);
		List<Product> products = dao.query(Product.class, Cnd.where("vendorid","=",v.getId()), page);
		page.setRecordCount(dao.count(Product.class));
		PageForm<Product> pf = new PageForm<Product>();
		pf.setPage(page);
		pf.setResultList(products);
		return pf;
	}
	@At("/product/preupdate")
	@Ok("tiles:vendor.product.preupdate")
	public ProductForm preUpdateProduct(@Param("productid")int productid){
		ProductForm pf = preUploadProduct();
		Product p = dao.fetch(Product.class,productid);
		pf.setProduct(p);
		return pf;
	}
	@At("/product/delete")
	@Ok("redirect:/vendor/product/manage")
	public void deleteProduct(@Param("ids")String[] ids){
		if(ids !=null && ids.length>0){
			for(String id : ids){
				if(!Strings.isEmpty(id))
					dao.delete(Product.class,Long.valueOf(id));
			}
		}
	}
	@At("/product/update")
	@Ok("redirect:/vendor/product/manage")
	@AdaptBy(type=UploadAdaptor.class,args={"E:/TomcatShare/temp"})
	public void updateProduct(@Param("::product.")Product product,@Param("image")File image){
		if(product.getId()==0) return;
		if(image != null && !Strings.isEmpty(Files.getSuffixName(image))){
			if(!Strings.isEmpty(product.getImage()))
				Files.deleteFile(new File(ApplicationUtil.getWebHomePath()+product.getImage()));
			String newFilePath =  IMAGE_UPLOAD_PATH+new StringGenerator(32, 32).next()+"."+Files.getSuffixName(image);
			log.debug("产品图片的url"+newFilePath);
			try {
				Files.copyFile(image, new File(ApplicationUtil.getWebHomePath()+newFilePath));
				product.setImage(newFilePath);
			} catch (IOException e) {
				log.error("产品上传图片出错了", e);
			}
		}
		dao.update(product);
	}
	@At("/message/manage")
	@Ok("tiles:vendor.message.manage")
	public PageForm<Message> manageMessage(@Param("pageNum")int pageNum,HttpServletRequest request){
		PageForm<Message>  pf = new PageForm<Message>();
		UserHolder uh = (UserHolder) request.getSession().getAttribute(BaseHttpFilter.SECURITY_SESSION_USER);
		User user = dao.fetch(User.class,uh.getUsername());
		Vendor v = dao.fetch(Vendor.class,Cnd.where("userid","=",user.getId()));
		Pager page = dao.createPager(pageNum<1?1:pageNum, 20);
		List<Message> messages = dao.query(Message.class, Cnd.wrap("productid in (select id from sh_product where vendorid="+v.getId()+")"),page);
		if(messages!=null && messages.size()>0){
			for(Message m : messages){
				dao.fetchLinks(m, "product");
				dao.fetchLinks(m, "user");
			}
		}
		page.setRecordCount(dao.count(Message.class, Cnd.wrap("productid in (select id from sh_product where vendorid="+v.getId()+")")));
		pf.setPage(page);
		pf.setResultList(messages);
		return pf;
	}
}
